package com.smartstate.ems.config;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.smartstate.ems.constant.CacheConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * mybatisPlus扩展接口，在进行操作时对指定字段进行填充
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private HttpServletRequest request;

    /**
     * 是否开启了插入填充
     */
    @Override
    public boolean openInsertFill() {
        return true;
    }

    /**
     * 是否开启了更新填充
     */
    @Override
    public boolean openUpdateFill() {
        return true;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        log.error("进入插入拦截");
        String now = (new DateTime()).toString();
        Object creatorObjectId = getFieldValByName("id", metaObject);
        if (creatorObjectId != null && StringUtils.isBlank(creatorObjectId.toString())) {
            String id = (char) (int) (Math.random() * 26 + 97) + IdUtil.fastSimpleUUID();
            this.setFieldValByName("id", id, metaObject);
        }
        this.setFieldValByName("createTime", new DateTime(), metaObject);
        this.setFieldValByName("updateTime", new DateTime(), metaObject);
//        获取当前用户id，因为还为实现登录，因此用户id为空
        try {
            String userId = request.getHeader(CacheConstants.DETAILS_USER_ID);
            if (StringUtils.isNotBlank(userId)) {
                this.setFieldValByName("createUser", userId, metaObject);
                this.setFieldValByName("id", IdUtil.simpleUUID(), metaObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.setFieldValByName("updateTime", new DateTime(), metaObject);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.error("进入修改拦截");
        String now = (new DateTime()).toString();
        String userId = null;
        try {
            if (request != null) {
                if ("Current HttpServletRequest".equals(request.toString()) == false) {
                    userId = request.getHeader(CacheConstants.DETAILS_USER_ID);
                    this.setFieldValByName("updateUser", userId, metaObject);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.setFieldValByName("updateTime", new DateTime(), metaObject);
    }
}